package kontrol;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import database.DALException;
import database.MySQLOperatoerDAO;
import database.MySQLRaavareBatchDAO;
import database.OperatoerDAO;
import database.OperatoerDTO;
import database.RaavareBatchDTO;

/**
 * Servlet implementation class Operator
 */
@WebServlet({ "/Operator", "/Operator/*" })
public class Operator extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private Validator validator;
	private MySQLOperatoerDAO oprDAO;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Operator() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// OperatoerDTO login = (OperatoerDTO) session.getAttribute("login");
		// if (login == null) {
		// request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request,
		// response);
		// return;
		// } else {
		if (request.getRequestURI().endsWith("Operator/AddUser")) {
			request.getRequestDispatcher("/WEB-INF/operator/createuser.jsp")
					.forward(request, response);
			// } else if
			// (request.getRequestURI().endsWith("Operator/ChangeUser")) {
			// request.getRequestDispatcher("/WEB-INF/operator/changeuser.jsp").forward(request,
			// response);
		} else if (request.getRequestURI().endsWith("Operator/DeleteUser")) {
			request.getRequestDispatcher("/WEB-INF/operator/deleteuser.jsp")
					.forward(request, response);

		} else if (request.getRequestURI().endsWith("Operator/ShowUser")) {
			formatOperatorList(request);
			request.getRequestDispatcher("/WEB-INF/operator/showuser.jsp")
					.forward(request, response);

		} else if (request.getRequestURI().endsWith("Operator/OperatorHome")) {
			request.getRequestDispatcher("/WEB-INF/operator/operatorhome.jsp")
					.forward(request, response);
		}
		return;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		OperatoerDTO dto = null;

		if (request.getParameter("newOperatoer") != null) {
			if ((request.getParameter("oprNavn") != null)
					&& (request.getParameter("ini") != null)
					&& (request.getParameter("cpr") != null)
					&& (request.getParameter("rolle") != null)) {

				validator = new Validator();

				int oprId = 0;

				String oprNavn = request.getParameter("oprNavn");
				String ini = request.getParameter("ini");

				String cpr = request.getParameter("cpr");
				String[] resultCpr = validator.validateCPR(cpr, "cpr");

				String kodeord = validator.generatePASSWORD();
				// String[] resultKodeord = validator.validatePASSWORD(kodeord,
				// "password");

				String rolle = request.getParameter("rolle");
				String[] resultRolle = validator.validateHELTAL(rolle, "role",
						1, 4);

				ArrayList<String[]> results = new ArrayList<String[]>();
				ArrayList<String[]> errors = new ArrayList<String[]>();

				results.add(resultCpr);
				results.add(resultRolle);

				for (int i = 0; i < results.size(); i++) {
					if (results.get(i)[2] != null)
						errors.add(results.get(i));
				}

				if (errors.isEmpty()) {
					int role = Integer.parseInt(request.getParameter("rolle"));
					dto = new OperatoerDTO(oprId, oprNavn, ini, cpr, kodeord,
							role);

					try {
						oprDAO = new MySQLOperatoerDAO();
						oprDAO.createOperatoer(dto);
						request.setAttribute("succes", "Operator created!");
					} catch (DALException e) {
						e.printStackTrace();
						request.setAttribute("errors", "Could not create object");
					}
				} else {
					request.setAttribute("errors", results);
				}
				request.getRequestDispatcher("/WEB-INF/operator/createuser.jsp").forward(request, response);
			}
		}

		else if (request.getParameter("delOperatoer") != null) {

			// delete user

			String change = request.getParameter("delOprId");
			int userId = -1;
			OperatoerDTO oprDTO;

			try {
				userId = Integer.parseInt(change);
			} catch (NumberFormatException e) {
				e.printStackTrace();
				System.out.println("Number Format Exception");
				request.setAttribute("errors","the entered value must be type of integer");
			}

			try {
				oprDAO = new MySQLOperatoerDAO();
				oprDTO = oprDAO.getOperatoer(userId);
				oprDAO.disableOperatoer(oprDTO);
				request.setAttribute("succes", "operator deleted from database!");
			} catch (DALException e) {
				e.printStackTrace();
				request.setAttribute("errors", "unable to delete operator from database");
			}
			request.getRequestDispatcher("/WEB-INF/operator/deleteuser.jsp").forward(request, response);
		}
	}

	public void formatOperatorList(HttpServletRequest request)
			throws ServletException, IOException {

		MySQLOperatoerDAO opDAO = null;
		try {
			opDAO = new MySQLOperatoerDAO();
			request.setAttribute("count", opDAO.getCount());
		} catch (DALException e) {
			e.printStackTrace();
			request.setAttribute("count", 0);
		}
		if (((Integer) request.getAttribute("count")) < 10) {
			try {
				List<OperatoerDTO> liste = opDAO.getOperatoerList();
				String results = "<table border=\"1\"> <tr> <th>Opr ID</th> <th>Opr Name</th> <th>Opr Ini</th> <th>Cpr</th> <th>Password</th> <th>Role</th> </tr>";
				for (int i = 0; i < liste.size(); i++) {
					results += "<tr> <td>" + liste.get(i).getOprId()
							+ "</td><td> " + liste.get(i).getOprNavn()
							+ "</td><td> " + liste.get(i).getIni()
							+ "</td><td> " + liste.get(i).getCpr()
							+ "</td><td> " + liste.get(i).getKodeord()
							+ "</td><td> " + liste.get(i).getRolle() + "<br>"
							+ "</td> </tr>";
				}
				results += "</table>";
				request.setAttribute("results", results);
			} catch (DALException e) {
				e.printStackTrace();
			}
		} else {
			if (request.getAttribute("page") == null) {
				request.setAttribute("page", 0);
			}
			if (request.getParameter("p") != null) {
				request.setAttribute("page",
						Integer.parseInt(request.getParameter("p")));
			}
			int curPage = (Integer) request.getAttribute("page");
			try {
				List<OperatoerDTO> liste = opDAO.getOperatoerList(curPage, 10);
				String results = "<table border=\"1\"> <tr> <th>Opr ID</th> <th>Opr Name</th> <th>Opr Ini</th> <th>Cpr</th> <th>Password</th> <th>Role</th> </tr>";
				for (int i = 0; i < liste.size(); i++) {

					results += "<tr> <td>" + liste.get(i).getOprId()
							+ "</td><td> " + liste.get(i).getOprNavn()
							+ "</td><td> " + liste.get(i).getIni()
							+ "</td><td> " + liste.get(i).getCpr()
							+ "</td><td> " + liste.get(i).getKodeord()
							+ "</td><td> " + liste.get(i).getRolle() + "<br>"
							+ "</td> </tr>";
				}
				results += "</table>";
				if (curPage > 9) {
					results += "<a href=\"?p=" + (curPage - 10)
							+ "\">Prev</a>&nbsp;&nbsp;&nbsp;";
				}
				if ((((Integer) request.getAttribute("count")) - 10) > curPage) {
					results += "<a href=\"?p=" + (curPage + 10) + "\">Next</a>";
				}

				request.setAttribute("results", results);
			} catch (DALException e) {
				e.printStackTrace();
			}
		}
	}

}